package user;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class User_RegisterServlet
 */
@WebServlet("/User_RegisterServlet")
public class User_RegisterServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public User_RegisterServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//response.getWriter().append("Served at: ").append(request.getContextPath());
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html; charset=UTF-8");
		request.setCharacterEncoding("utf-8");
		String uname = request.getParameter("username");
		String pass = request.getParameter("pass");
		String code = request.getParameter("code");
		String  phone = request.getParameter("phone");
		//System.out.println(code);
		UserDao dao = new UserDao();
		
		boolean result = dao.isExistsUname(uname);
		if(result) {
			//System.out.println("1");
			response.sendRedirect("/Lesson_310/user/user_success.jsp?count=5");
			return ;
		}
		//密码加密
		String ps = dao.string2MD5(pass);
		//获取其余的注册消息
		User user = new User();
		user.setUname(uname);
		user.setPass(ps);
		user.setSex(request.getParameter("sex"));
		user.setProfession(request.getParameter("profession"));
		user.setNote(request.getParameter("note"));
		String[] favourite_a = request.getParameterValues("favourite");//获取爱好
		String favourite = "";
		for(int i = 0; i <favourite_a.length;i++){
			favourite += favourite_a[i] + " ";
					}
		user.setFavourite(favourite);
		int row = dao.doRegister(user);
		if(row >= 0&&code.equals(phone)) {
			//response.sendRedirect("/Lesson_310/user/login.jsp");
			response.getWriter().print("<script type=\"text/javascript\">alert(\"注册成功！\");window.location=\"/Lesson_310/user/login.jsp\";</script>");
		}else {
			//response.sendRedirect("/Lesson_310/user/user_failure.jsp");
			response.getWriter().print("<script type=\"text/javascript\">alert(\"注册失败！\");window.location=\"/Lesson_310/user/resgistered.jsp\";</script>");
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
